package org.space.galaxyCabinet.handler.impl;

import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.space.galaxyCabinet.annotation.GuiguEmqx;
import org.space.galaxyCabinet.clients.DeviceStatusClients;
import org.space.galaxyCabinet.constant.EmqxConstants;
import org.space.galaxyCabinet.domain.DeviceBase;
import org.space.galaxyCabinet.domain.DeviceStatus;
import org.space.galaxyCabinet.handler.MassageHandler;
import org.space.galaxyCabinet.service.InfluxDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@GuiguEmqx(topic = EmqxConstants.SYS_DEVICE_ONLINE)
public class DeviceOnlineHandler implements MassageHandler {

    @Autowired
    private DeviceStatusClients deviceStatusClients;

    @Autowired
    private InfluxDBService influxDBService;

    @Override
    public void handleMessage(JSONObject message) {
        log.info(getClass().getName()+" => 开始处理设备属性上报消息...");
        try {
            // 检查消息是否为空
            if (message == null || message.isEmpty()) {
                log.warn("收到空消息");
                return;
            }
            DeviceBase deviceBase = new DeviceBase();
            deviceBase.setDeviceNo(message.getString("clientid"));
            if (message.getString("clean_start") != null) {
                deviceBase.setStatus(2);
                log.info("deviceBase:{}", JSONObject.toJSONString(deviceBase));
                log.info("修改设备状态在线：{}", deviceStatusClients.updateStatusByDeviceNo(deviceBase));      // 修改设备状态
            } else {
                deviceBase.setStatus(1);
                log.info("修改设备状态离线：{}", deviceStatusClients.updateStatusByDeviceNo(deviceBase));      // 修改设备状态
                DeviceStatus deviceStatusList = influxDBService.queryLastDeviceStatusByConditions(deviceBase.getDeviceNo());
                if (deviceStatusList != null) {
                    log.info("设置最后设备状态信息：{}", deviceStatusClients.updateByDeviceNo(deviceStatusList));
                }
                DeviceStatus deviceStatus = new DeviceStatus();
                deviceStatus.setDeviceNo(message.getString("clientid"));
                log.info("deviceBase:{}", JSONObject.toJSONString(deviceBase));
                log.info("修改最后在线时间：{}", deviceStatusClients.updateOnlineByDeviceNo(deviceStatus.getDeviceNo())); // 修改最后在线时间
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
